﻿package
{
	import flash.display.MovieClip;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import flash.display.GradientType;
	
	public class Reflection
	{
		//VARIABLES INTERNAS SETEABLES.
		private var clip:MovieClip;
		private var gradientRatio_uint:uint = 150;
		private var reflectionAlpha_num:Number = 0.25;
		private var offset_num:Number = 0;
		
		//SETTERS Y GETTERS.
		public function set targetClip(value:MovieClip):void {clip = value;}
		public function set gradientRatio(value:uint):void {gradientRatio_uint = value;}
		public function set reflectionAlpha(value:Number):void {reflectionAlpha_num = value;}
		public function set reflectionOffset(value:Number):void {offset_num = value;}
		
		//CONSTRUCTOR.
		public function Reflection() {}
		
		//INIT.
		public function init():MovieClip
		{
			//REDIBUJA EL SUBCLIP.
			var bmpData:BitmapData = new BitmapData(clip.subClip.width, clip.subClip.height, true, 0x00000000);
			var bmpDataMatrix = new Matrix();
			bmpDataMatrix.scale(-1, 1);
			bmpDataMatrix.rotate(Math.PI);
			bmpDataMatrix.translate(clip.subClip.width/2, clip.subClip.height/2);
			bmpData.draw(clip.subClip, bmpDataMatrix);
			
			//INSERTA EL BMPDATA EN UN CONTENEDOR.
			var bmp:Bitmap = new Bitmap(bmpData);
			
			//GENERA EL GRADIENTE.
			var grad:MovieClip = new MovieClip();
			var gradMatrix:Matrix = new Matrix();
			gradMatrix.createGradientBox(clip.subClip.width, clip.subClip.height, Math.PI/2, 0, 0);
			grad.graphics.lineStyle(1, 0, 0);
			grad.graphics.beginGradientFill(GradientType.LINEAR, [0xffffff, 0xffffff], [1, 0], [0, gradientRatio_uint], gradMatrix);
			grad.graphics.drawRect(0, 0, clip.subClip.width, clip.subClip.height);
			grad.graphics.endFill();
			
			//CONFORMA Y POSICIONA EL REFLEJO.
			var reflection:MovieClip = new MovieClip();
			reflection.addChild(bmp);
			reflection.addChild(grad);
			bmp.y = offset_num;
			grad.y = offset_num;
			bmp.alpha = reflectionAlpha_num;
			bmp.cacheAsBitmap = true;
			grad.cacheAsBitmap = true;
			bmp.mask = grad;
			reflection.x = -clip.subClip.width/2;
			reflection.y = clip.subClip.height/2;
			clip.addChild(reflection);
			
			//DEVUELVE UNA REFERENCIA AL REFLEJO.
			return reflection;
		}
	}
}